package com.newyear.concertManagementSystem.servlet;

import entity.Concert;
import service.ConcertService;
import service.impl.ConcertServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/page")
public class PageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        ConcertService concertService = new ConcertServiceImpl();
        int count = concertService.count();

        int currentPage = Integer.parseInt(request.getParameter("currentPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));

        int startIndex = (currentPage - 1) * pageSize;

        int totalPages = (count % pageSize == 0) ? (count / pageSize) : (count / pageSize + 1);

        if (currentPage < 1) {
            currentPage = 1;
        }

        if (pageSize < 1) {
            pageSize = 3;
        }

        if (currentPage > totalPages) {
            currentPage = totalPages;
        }
        
        List<Concert> list = concertService.page(startIndex, pageSize);

        request.setAttribute("list", list);
        request.setAttribute("count", count);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalPages", totalPages);

        request.getRequestDispatcher("page.jsp").forward(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
